<?php
namespace Chat\Controller;

require_once __DIR__.'/../GatewayClient/Gateway.php';
use GatewayClient\Gateway;
Gateway::$registerAddress = '127.0.0.1:1238';
class ChatController extends BaseController{

    public function _initialize(){
        parent::_initialize();
    }

    public function chat()
    {
        $to_uid = I('to_uid', 0);
        $kf_id = I('kf_id');
        if(empty($to_uid) && empty($kf_id)){
            exit('访问地址错误');
        }
        $weObj = new \Org\Util\Wechat(C('options'));
        // if($this->user_type == 'customer'){
        if($kf_id){
            // 客户访问
            $kf = M('kf')->where(['id'=>$kf_id])->find();
            if(empty($kf)){
                exit('客服不存在');
            }
            $customer=M('customer')->where(['openid'=>$kf['openid']])->find();
            if (empty($customer)) {
                exit('客服未注册');
            }
            $to_uid = $customer['id'];
            $to_user = [
                'nickname'  => !empty($kf) ? $kf['kf_nickname'] : '',
                'avatar'    => !empty($kf) ? $kf['kf_headimgurl'] : '',
            ];
            $userinfo = $weObj->getUserInfo($this->openid);
            if($userinfo){
                $user = [
                    'nickname'  => $userinfo['nickname'],
                    'avatar'    => $userinfo['headimgurl'],
                ];
                $this->assign('user', $user);
            }
            $this->assign('access_type', 'customer');
        }else{
            // 客服访问
            $to_user = [
                'nickname'  => '',
                'avatar'    => '',
            ];
            $userInfo = M('customer')->where(['id'=>$to_uid])->find();
            if($userInfo){
                $userinfo = $weObj->getUserInfo($userInfo['openid']);
                if($userinfo){
                    $to_user = [
                        'nickname'  => $userinfo['nickname'],
                        'avatar'    => $userinfo['headimgurl'],
                    ];
                }
                $to_user['nickname'] = $userInfo['note_name'] ? $userInfo['note_name'] : $userInfo['name'];
            }
            $this->assign('access_type', 'kefu');
        }
        $tplNoticeModel = M('user_message_tpl_notice');

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $js_config = $weObj->getJsSign($url);

        // 对方发送给我的 消息模板通知改为时效
        $tplNoticeModel->where(['from_uid'=>$to_uid, 'to_uid'=>$this->user_id])->save(['status'=>2]);
        $this->assign('to_uid', $to_uid);
        $this->assign('to_user', $to_user);
        $this->assign('js_config', $js_config);
        $this->display();
    }

    public function bind()
    {
        $client_id = I('client_id');
        $to_uid = I('to_uid');
        Gateway::bindUid($client_id, $this->user_id);
        if($to_uid){
            $session = [
                'to_uid'    => $to_uid,
            ];
            Gateway::setSession($client_id, $session);
        }
        $this->ajaxReturn(['status'=>1, 'user_id'=>$this->user_id]);
    }

    public function send_msg()
    {
        $data = I('post.');
        // Gateway::sendToAll(json_encode($data));
        $model = D('Message');
        if($data){
            switch ($data['event']) {
                case 'init':
                    break;
                case 'ping':
                    break;
                case 'say':
                    $to_uid = $data['to_uid'];
                    $customer = $this->customerInfo($this->user_id);
                    $toCustomer = $this->customerInfo($to_uid);
                    $access_type = $data['access_type'];
                    if(empty($toCustomer)){
                        $this->ajaxReturn(['status'=>0, 'msg'=>'对方未注册，发送失败。']);
                    }
                    if(!Gateway::isUidOnline($this->user_id)){
                        // 自己未在线
                        $this->ajaxReturn(['status'=>0, 'msg'=>'未连接服务器，发送失败。']);
                    }
                    // 记录库
                    $addRes = $model->addMsg($this->user_id, $to_uid, $data['content'], $data['msg_type']);
                    $to_online = 0;
                    if($addRes['status'] == 1){
                        // 是否要发送模板通知对方
                        $tpm_notice = false;
                        // 对方接收消息状态
                        $to_status = 0;
                        // 对方在线
                        if(Gateway::isUidOnline($to_uid)){
                            $to_online = 1;
                            // 自己client_id
                            $client_id = Gateway::getClientIdByUid($this->user_id);
                            // 对方client_id
                            $to_client_id = Gateway::getClientIdByUid($to_uid);
                            // 对方和谁在线
                            $session = Gateway::getSession($to_client_id[0]);
                            if($session && $session['to_uid']!=$this->user_id){
                                // 对方没和自己连线
                                // 发送消息模板通知
                                $tpm_notice = true;
                            }else{
                                $to_status = 1;
                                $tpm_notice = false;
                                if($session && $session['to_uid']==$this->user_id){
                                    // 在线发送消息
                                    Gateway::sendToUid($to_uid, json_encode(['event'=>'msg', 'msg_id' => $addRes['id'], 'from_uid'=>$this->user_id, 'msg_type'=>$data['msg_type'], 'time'=>time(), 'content'=>$data['content']]));
                                }else{
                                    // 在线发送消息
                                    Gateway::sendToUid($to_uid, json_encode(['event'=>'msg', 'msg_id' => $addRes['id'], 'from_uid'=>$this->user_id, 'msg_type'=>$data['msg_type'], 'time'=>time(), 'content'=>$data['content'], 'nickname'=>$customer['nickname'], 'avatar'=>$customer['avatar']]));  
                                }
                            }
                        }else{
                            // 对方未在线
                            $tpm_notice = true;
                        }
                        $to_openid = '';
                        if($tpm_notice){
                            $tplNoticeModel = M('user_message_tpl_notice');
                            $lastNotice = $tplNoticeModel->where(['from_uid'=>$this->user_id, 'to_uid'=>$to_uid])->order('id desc')->find();
                            // 未发送过通知 或 最后的通知已读过时效
                            if(empty($lastNotice) || $lastNotice['status'] == 2){
                                $to_openid = $toCustomer['openid'];
                                // 对方类型
                                // switch ($toCustomer['customer_type']) {
                                // 发送者角色
                                switch ($access_type) {
                                    case 'customer':
                                        // 发送模板消息
                                        $xq = M('Apt')->where(array('id'=>$customer['plot']))->find();
                                        $xqTitle = empty($xq['name'])?'尚云':$xq['name'];//小区名称
                                        $user_nickname = $customer['name'];//用户姓名
                                        $kf_account = '';//客服账号
                                        $weObj = new \Org\Util\Wechat(C('options'));
                                        $url = U('chat', ['to_uid'=>$this->user_id], true, true);
                                        $tplData =  array(
                                            "touser"        => $to_openid,
                                            "template_id"   => "Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
                                            "url"           => $url,
                                            "topcolor"      => "#FF0000",
                                            "data"          => array( 
                                                'first' =>  array(
                                                    "value" => "您有新的咨询信息通知",
                                                    "color" => "#ff0000"
                                                ),
                                                'keyword1'  => array(
                                                    "value" => $xqTitle,
                                                    "color" => "#173177"
                                                ),
                                                'keyword2'  => array(
                                                    "value" => '咨询通知',
                                                    "color" => "#173177"
                                                ),
                                                'keyword3'  => array(
                                                    "value" => "您好，".$xqTitle."的".$user_nickname."要咨询您一些有问题，看到后请及时回复",
                                                    "color" => "#173177"
                                                ),  
                                                'remark'    => array(
                                                    "value" => "点击查看",
                                                    // "color" => "#173177"
                                                )
                                            )
                                        );
                                        // $st = true;
                                        $st = $weObj->sendTemplateMessage($tplData);
                                        break;
                                    case 'kefu':
                                        $kf_id = $customer['kf_id'];
                                        $url = U('chat', ['kf_id'=>$kf_id], true, true);

                                        $xq = M('Apt')->where(array('id'=>$toCustomer['plot']))->find();
                                        $xqTitle = empty($xq['name'])?'尚云':$xq['name'];//小区名称
                                        $user_nickname = $customer['name'];//用户姓名
                                        $kf_account = '';//客服账号
                                        $weObj = new \Org\Util\Wechat(C('options'));

                                        if($data['msg_type'] == 'image'){
                                            $content = '图片';
                                        }else{
                                            $content = $data['content'];
                                        }
                                        $tplData =  array(
                                            "touser"        => $to_openid,
                                            "template_id"   => "Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
                                            "url"           => $url,
                                            "topcolor"      => "#FF0000",
                                            "data"          => array( 
                                                'first' =>  array(
                                                    "value" => "您有新的咨询回复通知",
                                                    // "color" => "#ff0000"
                                                ),
                                                'keyword1'  => array(
                                                    "value" => $xqTitle,
                                                    "color" => "#173177"
                                                ),
                                                'keyword2'  => array(
                                                    "value" => '咨询回复',
                                                    "color" => "#173177"
                                                ),
                                                'keyword3'  => array(
                                                    "value" => $content,
                                                    "color" => "#173177"
                                                ),  
                                                'remark'    => array(
                                                    "value" => "点击查看",
                                                    // "color" => "#173177"
                                                )
                                            )
                                        );
                                        // $st = true;
                                        $st = $weObj->sendTemplateMessage($tplData);
                                        break;
                                    default:
                                        break;
                                }
                                if(!empty($st)){
                                    //微信模板发送成功 添加到模板通知记录
                                    $tplNoticeModel->add([
                                        'from_uid'      => $this->user_id,
                                        'to_uid'        => $to_uid,
                                        'status'        => 1,
                                        'create_time'   => time(),
                                    ]);
                                }
                            }
                        }
                        $resData = [
                            'event'     => 'say_res',
                            'msg_id'    => $addRes['id'],
                            'status'    => 1,
                            'to_status' => $to_status,
                            'to_online' => $to_online,
                            'say_id'    => $data['say_id'],
                            'time'      => time(),
                            'to_openid' => $to_openid,
                        ];
                        if($data['msg_type'] == 'image'){
                            $resData['img'] = $data['content'];
                        }
                        Gateway::sendToUid($this->user_id, json_encode($resData));
                    }else{
                        Gateway::sendToUid($this->user_id, json_encode(['event'=>'say_res', 'status'=>0, 'say_id'=>$data['say_id']]));
                    }
                    break;
                case 'recall':
                    $msg_id = $data['msg_id'];
                    $has = M('user_message')->where(['id'=>$msg_id])->find();
                    if(empty($has)){
                        $this->ajaxReturn(['status'=>1, 'msg'=>'ok']);
                    }
                    if($has['from_uid']!=$this->user_id){
                        $this->ajaxReturn(['status'=>0, 'msg'=>'撤销错误']);
                    }
                    $delRes = M('user_message')->where(['id'=>$msg_id])->delete();
                    if($delRes){
                        if(Gateway::isUidOnline($has['to_uid'])){
                            Gateway::sendToUid($has['to_uid'], json_encode(['event'=>'recall', 'msg_id' => $msg_id, 'from_uid'=>$this->user_id]));
                        }
                        $this->ajaxReturn(['status'=>1, 'msg'=>'ok']);
                    }else{
                        $this->ajaxReturn(['status'=>0, 'msg'=>'撤销执行错误']);
                    }
                    break;
                default:
                    break;
            }
        }
        $model->db()->close();
        $this->ajaxReturn(['status'=>1, 'data'=>$data]);
    }
}